import axios from 'axios'
import VueCookies from 'vue-cookies'
import {Loading} from 'element-ui';

var Utils = {}

Utils.$http = axios;

Utils.ajaxCount = 0;


/**
 * Gets the json. 获取json数据
 *
 * @param      {<type>}    url      url
 * @param      {Function}  success  成功回调
 * @param      {Function}  error    失败回调
 * @param      {string}    params   参数
 */
Utils.getJson = function (url, success, error, params = {}, isShowPop = false, urlParams, method = "post", isFile) {
  if (!url) return;
  var loadingInstance;
  if (isShowPop) {
    loadingInstance = Loading.service({
      fullscreen: true,
      customClass: 'loading page-loading'
    });
  }
  //Utils.ajaxCount++;
  var opts = {
    method,
    url: url,
    timeout: 35000,//毫秒
    data: params,
    params: urlParams
  }
  if (isFile) {
    opts.headers = {
      'Content-Type': 'multipart/form-data'
    }
  }
  Utils.$http(opts)
    .then(function (res) {
      // if(!(--Utils.ajaxCount) && isShowPop) {
      // 	loadingInstance.close()
      // }
      if (isShowPop) {
        loadingInstance.close()
      }

      if (res.data.succflag == '0' || res.data.status === 0 || res.code === 0) {
        if (typeof success == 'function') success(res.data)
      } else if (res.data.succflag == '2') {	//令牌无效则退出刷新
        VueCookies.remove(Utils.CONFIG.cookieKey);
        VueCookies.remove(Utils.CONFIG.cookieKeyApp);
        // window.location.reload();
        if (localStorage.getItem('differentDevices')) {
          window.location.href = localStorage.getItem('differentDevices');
        } else {
          window.location.reload();
        }
      } else {
        if (typeof error == 'function') error(res.data)
      }
    }, function (err) {
      if (isShowPop) {
        loadingInstance.close();
      }
      if (typeof error == 'function') error(err)
    })
}

export default Utils